let departmentadd = (function () {
  let $departmentName = $("#departmentName"),
    $departmentDesc = $("#departmentDesc"),
    $submit = $(".submit"),
    departmentId = null;

  // 添加部门信息（同时判断是新增还是修改）
  function submitHandle() {
    $submit.click(async _ => {
      if (departmentId) {
        // /department/update
        let params = {
          departmentId,
          name: $departmentName.val().trim(),
          desc: $departmentDesc.val().trim()
        }
        let result = await axios.post('/department/update', params);
        if (result.code === 0) {
          alert(`成功修改了编号为${departmentId}的部门信息`);
          window.location.href = 'departmentlist.html';
          return;
        }
        alert('删除失败，请重试！');
        return;
      }
      // 新增
      let params = {
        name: $departmentName.val().trim(),
        desc: $departmentDesc.val().trim()
      };
      if (params.name.length === 0 || params.desc.length === 0) {
        alert("请填写，不能为空!");
        return;
      }
      let result = await axios.post("/department/add", params);
      if (result.code === 0) {
        alert("添加成功");
        window.location.href = 'departmentlist.html';
        return;
      }
      alert("添加失败，请重试");
    })
  }
  async function bindDepartmentInfo() {
    let result = await axios.get('/department/info', { params: { departmentId } });
    if (result.code === 0) {
      let { name, desc } = result.data;
      $departmentName.val(name);
      $departmentDesc.val(desc);
      return;
    }
    // 如果是失败了的话，最好把departmentId置为null，因为点击事件那里还需要用到判断
    departmentId = null;
  }
  return {
    init() {
      // 获取传递参数
      let params = window.location.href.queryURLParams();
      if (params.hasOwnProperty("departmentId")) {
        departmentId = params.departmentId;
        bindDepartmentInfo();
      }
      submitHandle();
    }
  }
})();
departmentadd.init();